import 'dart:typed_data';
import 'dart:ui';

import 'package:dujitang/toast.dart';
import 'package:flutter/material.dart';
import 'package:dujitang/global.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

class ContentPage extends StatefulWidget {
  ContentPage({Key key, this.data, this.onRefresh}) : super(key: key);
  final data;
  final onRefresh;

  @override
  _ContentPageState createState() => _ContentPageState();
}

class _ContentPageState extends State<ContentPage> {
  GlobalKey globalKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }

  Future<Uint8List> _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          globalKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      var status = await Permission.storage.status;
      print(status.isUndetermined);
      final result = await ImageGallerySaver.saveImage(pngBytes,
          quality: 100, name: "喂你毒鸡汤-" + widget.data['date'].toString());
      Toast.show(context,
          msg: '图片保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
    } catch (e) {
      print(e);
    }
    return null;
  }

  List<Widget> renderText(text) {
    List<Widget> list = [];
    text.forEach((item) {
      list.add(
        Text(
          item.toString(),
          maxLines: 3,
          style: TextStyle(
            color: Global.fontColor,
            fontSize: 23,
            fontWeight: FontWeight.w300,
          ),
        ),
      );
      list.add(SizedBox(height: 10));
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return widget.data == null
        ? Container()
        : Container(
            padding: EdgeInsets.all(10),
            width: MediaQuery.of(context).size.width,
            // height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Global.backgroundColor,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                RepaintBoundary(
                  key: globalKey,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      SizedBox(height: 40),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            widget.data['date'],
                            style: TextStyle(
                              color: Global.fontSecondColor,
                              fontSize: 15,
                              fontWeight: FontWeight.w400,
                            ),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Transform(
                            transform: Matrix4.identity()..scale(1.2, 1),
                            alignment: Alignment.center,
                            child: Text(
                              widget.data['day'].toString(),
                              style: TextStyle(
                                color: Global.fontColor.withOpacity(.8),
                                fontSize: 180,
                                fontWeight: FontWeight.w100,
                              ),
                            ),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '星期' + widget.data['weekday'].toString(),
                            style: TextStyle(
                              color: Global.fontSecondColor,
                              fontSize: 15,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                          SizedBox(width: 10),
                          Container(
                            width: 1,
                            height: 10,
                            decoration: BoxDecoration(
                              border: Border(
                                left: BorderSide(
                                  color: Global.fontSecondColor.withOpacity(.3),
                                  width: 1.5,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          Text(
                            widget.data['weekdayEn'].toString(),
                            style: TextStyle(
                              color: Global.fontSecondColor,
                              fontSize: 15,
                              fontWeight: FontWeight.w400,
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 20),
                      Container(
                        width: MediaQuery.of(context).size.width,
                        padding: EdgeInsets.all(30),
                        margin: EdgeInsets.all(20),
                        decoration: BoxDecoration(
                          border: Border(
                            top: BorderSide(
                              color: Global.fontSecondColor.withOpacity(.1),
                              width: .5,
                            ),
                          ),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: renderText(widget.data['text']),
                        ),
                      ),
                      SizedBox(height: 20),
                    ],
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    IconButton(
                      icon: Icon(Icons.refresh),
                      color: Global.fontColor,
                      iconSize: 30,
                      onPressed: () {
                        widget.onRefresh();
                      },
                    ),
                    SizedBox(width: 40),
                    IconButton(
                      icon: Icon(Icons.file_download),
                      color: Global.fontColor,
                      iconSize: 30,
                      onPressed: () {
                        _capturePng();
                      },
                    ),
                  ],
                )
              ],
            ),
          );
  }
}
